<template>
  <div class="dashboard-container">
    <div class="app-container">
      <pageTool :show-before="false">
        <template #after>
          <el-button type="primary" size="mini" @click="$router.push('/employees/import')">导入</el-button>
          <el-button type="primary" size="mini" @click="excelExport">导出</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="showDialog = true">新增员工</el-button>
        </template>
      </pageTool>
      <el-card class="box-card card-table">
        <!-- 表格 -->
        <el-table
          ref="table"
          :data="employeesList"
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="150" align="center" />
          <el-table-column prop="username" label="姓名" width="150" sortable align="center" />
          <el-table-column prop="avator" label="头像" width="150" align="center">
            <template v-slot="{row}">
              <img
                v-imgError="require('../../assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="width:50px ; height:50px"
                @click="clickAvatar(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" width="150" sortable align="center" />
          <el-table-column prop="workNumber" label="工号" width="120" sortable align="center" />
          <el-table-column prop="formOfEmployment" label="聘用形式" width="170" sortable align="center">
            <template v-slot="{row}">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column label="部门" width="170" sortable align="center">
            <template v-slot="{row}">
              {{ row.departmentName || '未知' }}
            </template>
          </el-table-column>
          <el-table-column
            label="入职时间"
            width="150"
            sortable
            align="center"
          >
            <template scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120" sortable align="center">
            <template scope="scope">
              {{ scope.row.enableState ? '可用' : '不可用' }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" align="center">
            <template scope="scope">
              <el-button :disabled="checkPermission(points.pointUserUpdate)" type="text" size="mini" @click="$router.push('/employees/details/'+scope.row.id)">查看</el-button>
              <el-button type="text" size="mini">转正</el-button>
              <el-button :disabled="checkPermission(points.pointUserSetJob)" type="text" size="mini">调岗</el-button>
              <el-button type="text" size="mini">离职</el-button>
              <el-button type="text" size="mini" @click="roleControl(scope.row.id)">角色</el-button>
              <el-button :disabled="checkPermission(points.pointUserDelete)" type="text" size="mini" @click="delEmployess(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="page.page"
          :page-size="page.pagesize"
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
    <!-- 页面加载 会加载dialog 但是不会加载内容 , 当dialog显示时才会加载内容 , 但是数据数据更新同步视图是异步的 , 因此需要$nextTick -->
    <el-dialog class="qrcode" :visible.sync="isShowAvaDialog">
      <canvas ref="qrcode" />
    </el-dialog>

    <!-- 角色对话框 -->
    <control-role :show-role-dialog.sync="showRoleDialog" :role-id="currentRoleId" />
    <AddEmployees :show-dialog.sync="showDialog" @refresh="getEmployeesList" />
    <!-- <AddEmployees v-model="showDialog" /> -->
  </div>
</template>

<script>
import { getEmployeesListAPI, DelEmployeesAPI } from '@/api/employees'
import AddEmployees from './components/addEmployees.vue'
import { formatHireType } from '@/filters/filter'
// import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/utils'
import QRCode from 'qrcode'
import img from '../../assets/common/bigUserHeader.png'
import ControlRole from './components/controlRole.vue'
import premission from '@/mixins/premission'
export default {
  name: 'Employees',
  components: {
    AddEmployees,
    ControlRole
  },
  mixins: [premission],
  data() {
    return {
      page: {
        page: 1,
        size: 10
      },
      rolepage: {
        page: 1,
        size: 100
      },
      employeesList: [], // 员工列表
      roleList: [],
      total: null,
      showDialog: false,
      img,
      isShowAvaDialog: false,
      showRoleDialog: false,
      currentRoleId: ''
    }
  },
  updated() {
    // console.log('update, 视图更新了', this.employeesList)
  },

  created() {
    this.getEmployeesList()
  },
  mounted() {
    // console.log('mounted', this.employeesList)
  },
  methods: {

    // 获取员工信息
    async getEmployeesList() {
      const res = await getEmployeesListAPI(this.page)
      // console.log('数据回来了')
      this.employeesList = res.rows
      this.total = res.total
    },
    // 页码发生变化
    async  handleCurrentChange(value) {
      this.page.page = value

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      await this.getEmployeesList()
      loading.close()
    },
    // 删除员工
    async delEmployess(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        type: 'warning'
      }).then(async() => {
        await DelEmployeesAPI(id)
        this.getEmployeesList()
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    // 导出excel
    excelExport() {
      // 映射关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载文件
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows: data } = await getEmployeesListAPI({ page: 1, size: this.total })
        // 处理数据

        const arr = this.formatExcel(data, headers)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填 []
          data: arr, // 具体数据 必填 [[],[]]
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    formatExcel(data, headers) {
      return data.map(item => {
        return Object.keys(headers).map(key => {
          if ((item[headers[key]] - 0 > 0) && (key === '入职日期' || key === '转正日期')) {
            return formatDate(item[headers[key]], '/')
          }
          if (key === '聘用形式') return formatHireType(item[headers[key]])
          return item[headers[key]] ? item[headers[key]] : '暂未设置'
        })
      })
    },
    // 点击头像
    clickAvatar(url) {
      if (!url) return this.$message.error('暂未设置头像')
      this.isShowAvaDialog = true
      this.$nextTick(() => {
        const canvas = this.$refs.qrcode
        QRCode.toCanvas(canvas, url, function(error) {
          if (error) console.error(error)
          console.log('success!')
        })
      })
    },
    // 点击角色
    async roleControl(id) {
      this.currentRoleId = id
      this.showRoleDialog = true
    }
  }
}
</script>

<style scoped lang='scss'>

.card-table {
  margin-top: 10px;
}
.el-pagination {
  text-align: right;
}
::v-deep .qrcode .el-dialog {
  width: 300px;
  text-align: center;
}
</style>
